use flutter_rust_bridge::frb;
use rdev::{listen, Key};
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::channel;
use std::thread::{self, sleep};
use std::time::Duration;
use serde::Serialize;
use crate::frb_generated::StreamSink;
use once_cell::sync::OnceCell;

#[derive(Debug, Clone, Serialize)]
pub struct InputEvent {
    pub state: String, // "keyboard" 或 "mouse"
    pub x: f64, // "keyboard" 或 "mouse"
    pub y: f64,     // 具体按键/坐标
}

// 使用 lazy_static 创建全局缓存
pub static PATHS: OnceCell<HashMap<String, String>> = OnceCell::new();

static CTRL: AtomicBool = AtomicBool::new(false);
static SHIFT: AtomicBool = AtomicBool::new(false);
static A: AtomicBool = AtomicBool::new(false);

#[frb]
pub fn start_listen_input(sink: StreamSink<String>) {
    let (schan, rchan) = channel();
    let _listener = thread::spawn(move || {
        listen(move |event| {
            schan
                .send(event)
                .unwrap_or_else(|e| println!("Could not send event {:?}", e));
        })
        .expect("Could not listen");
    });

    let mut m_x: f64 = 0.0;
    let mut m_y: f64 = 0.0;
    let mut m_x_send: f64 = 0.0;
    let mut m_y_send: f64 = 0.0;
    let mut is_show = false;

    for event in rchan.iter() {
        match event.event_type {
            rdev::EventType::KeyPress(key) => {
                match key {
                    Key::ControlLeft => {
                        let _ = CTRL.store(true, std::sync::atomic::Ordering::SeqCst);
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) 
                        && SHIFT.load(std::sync::atomic::Ordering::SeqCst) 
                        && A.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "screenshot".to_string()
                            };
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    Key::ControlRight => {
                        let _ = CTRL.store(true, std::sync::atomic::Ordering::SeqCst);
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) 
                        && SHIFT.load(std::sync::atomic::Ordering::SeqCst) 
                        && A.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "screenshot".to_string()
                            };
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    Key::ShiftLeft => {
                        let _ = SHIFT.store(true, std::sync::atomic::Ordering::SeqCst);
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) 
                        && SHIFT.load(std::sync::atomic::Ordering::SeqCst) 
                        && A.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "screenshot".to_string()
                            };
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    Key::ShiftRight => {
                        let _ = SHIFT.store(true, std::sync::atomic::Ordering::SeqCst);
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) 
                        && SHIFT.load(std::sync::atomic::Ordering::SeqCst) 
                        && A.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "screenshot".to_string()
                            };
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    Key::KeyA => {
                        let _ = A.store(true, std::sync::atomic::Ordering::SeqCst);
                        
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) 
                        && SHIFT.load(std::sync::atomic::Ordering::SeqCst) 
                        && A.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "screenshot".to_string()
                            };
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    _ => {}
                }
            }
            rdev::EventType::KeyRelease(key) => {
                match key {
                    Key::ControlLeft => {
                        let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                    }
                    Key::ControlRight => {
                        let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                    }
                    Key::ShiftLeft => {
                        let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                    }
                    Key::ShiftRight => {
                        let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                    }
                    Key::KeyA => {
                        let _ = A.store(false, std::sync::atomic::Ordering::SeqCst);
                    }
                    _ => {}
                }
            }
            rdev::EventType::ButtonPress(button) => {
                match button {
                    rdev::Button::Left => {
                        if CTRL.load(std::sync::atomic::Ordering::SeqCst) && SHIFT.load(std::sync::atomic::Ordering::SeqCst) {
                            let event = InputEvent {
                                x:m_x, y:m_y, state: "show".to_string()
                            };
                            m_x_send = m_x;
                            m_y_send = m_y;
                            is_show = true;
                            let json = serde_json::to_string(&event).unwrap();
                            sink.add(json);
                            let _ = SHIFT.store(false, std::sync::atomic::Ordering::SeqCst);
                            let _ = CTRL.store(false, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    rdev::Button::Right => {}
                    rdev::Button::Middle => {}
                    rdev::Button::Unknown(_) => {}
                }
            }
            rdev::EventType::ButtonRelease(button) => {}
            rdev::EventType::MouseMove { x, y } => {
                m_x = x;
                m_y = y;
                if is_show {
                    if x - m_x_send > 150.0 || y - m_y_send > 150.0 || m_x_send - x > 150.0 || m_y_send - y > 150.0 {
                        let event = InputEvent {
                            x:m_x_send, y:m_y_send, state: "hide".to_string()
                        };
                        is_show = false;
                        let json = serde_json::to_string(&event).unwrap();
                        sink.add(json);
                    }
                }
            }
            rdev::EventType::Wheel { delta_x, delta_y } => {  
            }
        }
    }


}



#[frb]
pub fn simulated_mouse(x: i32, y: i32) {
    use rdev::{simulate, EventType, Button};
    sleep(Duration::from_millis(200));
    println!("simulated_mouse x:{} y:{}", x, y);
    let _ = simulate(&EventType::MouseMove { x: x as f64, y: y as f64 });
    let _ = simulate(&EventType::ButtonPress(Button::Left));
    sleep(Duration::from_millis(200));
    let _ = simulate(&EventType::ButtonRelease(Button::Left));
}